# server/src/search/baidu.py
import os
import requests
from .base import SearchProvider
from loguru import logger
import json
import hashlib
import time

class BaiduSearch(SearchProvider):
    def __init__(self):
        self.api_key = os.getenv("BAIDU_API_KEY")
        self.secret_key = os.getenv("BAIDU_SECRET_KEY")
        self.endpoint = "http://api.baidu.com/json/tongji/v1/ReportService/getData"
        
        if not self.api_key or not self.secret_key:
            logger.warning("百度API密钥未配置，搜索功能不可用")

    def _generate_signature(self, params: dict) -> str:
        """生成百度API签名"""
        param_str = ''.join([f"{k}{v}" for k,v in sorted(params.items())])
        return hashlib.md5((param_str + self.secret_key).encode()).hexdigest()

    def search(self, query: str, num_results: int = 3) -> str:
        try:
            if not self.api_key or not self.secret_key:
                raise ValueError("百度API密钥未配置")

            # 构造请求参数
            params = {
                "query": query,
                "apiKey": self.api_key,
                "timestamp": str(int(time.time())),
                "pageSize": num_results,
                "pageNum": 1
            }
            params["signature"] = self._generate_signature(params)

            response = requests.post(
                self.endpoint,
                json=params,
                headers={"Content-Type": "application/json"},
                timeout=15
            )
            response.raise_for_status()

            # 解析百度返回格式
            results = []
            data = response.json().get("result", {}).get("items", [])
            for item in data[:num_results]:
                results.append({
                    "name": item.get("title"),
                    "snippet": item.get("abstract"),
                    "url": item.get("url")
                })

            return json.dumps(results, ensure_ascii=False)[:1500]

        except Exception as e:
            logger.error(f"百度搜索失败：{str(e)}")
            return None